/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "database.h"
#include <cstdarg>
#include "node/sys/console.h"
#include "node/util/string.h"
using Console = ::node::sys::Console;

namespace node {
    namespace rdb {

        Database::Database(void)
            : conn_()
        {

        }

        Database::~Database(void)
        {

        }

        void Database::EscapeString(::std::string &sql)
        {

        }

        ::node::rdb::ResultSet *Database::Query(const char *sql, ...)
        {
            char lsql[MAX_QUERY_LENGTH];

            std::va_list varg;
            va_start(varg, sql);
            int ret = ::node::util::vsnprintf(lsql, MAX_QUERY_LENGTH, sql, varg);
            va_end(varg);

            if (ret == -1)
            {
                Console::Warning("SQL Query truncated (and not execute) for format: %s\n", sql);
                return NULL;
            }

            ::node::rdb::ResultSet *rs = conn_->Query(lsql);
            if (!rs && conn_->IsError()) {
                Console::Error("[Database::Query] %s\n", conn_->get_err_message().c_str());
            }
            return rs;
        }

        bool Database::Execute(const char *sql, ...)
        {
            char lsql[MAX_QUERY_LENGTH];

            std::va_list varg;
            va_start(varg, sql);
            int ret = ::node::util::vsnprintf(lsql, MAX_QUERY_LENGTH, sql, varg);
            va_end(varg);

            if (ret == -1)
            {
                Console::Warning("SQL Query truncated (and not execute) for format: %s\n", sql);
                return false;
            }

            if (!conn_->Execute(lsql)) {
                Console::Error("[Database::Execute] %s\n", conn_->get_err_message().c_str());
                return false;
            }

            return true;
        }

    }
}